package com.avidys.jwom.server;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.avidys.common.gwt.game.wom.model.Server;
import com.avidys.common.gwt.game.wom.model.ServerNotFoundException;
import com.avidys.common.gwt.game.wom.model.ServerService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class ServerServiceImpl extends RemoteServiceServlet implements ServerService {

	  private static final Logger LOG = Logger.getLogger(GameServiceImpl.class.getName());
	  private static final PersistenceManagerFactory PMF =
	      JDOHelper.getPersistenceManagerFactory("transactions-optional");

	  private PersistenceManager getPersistenceManager() {
	    return PMF.getPersistenceManager();
	  }

    PersistenceManager pm = getPersistenceManager();

	private int ERROR_OK = 0;

	public int addServer(Server s) {
	    // checkLoggedIn();
	    PersistenceManager pm = getPersistenceManager();
	    try {
	      pm.makePersistent(new ServerJDO(s));
	    } finally {
	      pm.close();
	    }
//        UserService userService = UserServiceFactory.getUserService();
 //       User user = userService.getCurrentUser();

//       Date date = new Date();
//        Server Server = new Server("Alfred", "Smith", new Date());

//        ServerJDO sjdo = new ServerJDO(s);
//		pm.makePersistent(sjdo);
		return ERROR_OK ;
	}

	public Server[] listServers() {
		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		
		Server[] res;
		// String query = "select from " + Server.class.getName() + " order by name";
	    PersistenceManager pm = getPersistenceManager();
		try {
	    String queryS = "select from " + ServerJDO.class.getName();
        List<ServerJDO> results = (List<ServerJDO>) pm.newQuery(queryS).execute();
        
	    if (results.isEmpty()) {
	    	res = null;
	    } else {
	        res = new Server[results.size()];
	        int i =0;
	        for (ServerJDO s : results) {
	        	res[i++] = new Server(s.name,s.url,s.desc);
            }
	    }
		} catch (Exception e) {
	    	res=null;
	    }finally{
//	        query.closeAll();
		    pm.close();
	    }
	    return res;
	    
//        Date date = new Date();
//		return "Hello, " + input + "!<br><br>I am running " + serverInfo
//				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}

	public Server getServers(String key) {
//		Key k = KeyFactory.createKey(Server.class.getUrl(), "Alfred.Smith@example.com");
//		 Key k = KeyFactory.createKey(Employee.class.getSimpleName(), 52234);
	    PersistenceManager pm = getPersistenceManager();
		ServerJDO s = pm.getObjectById(ServerJDO.class, key);
		return new Server(s.url,s.name,s.desc);
	}

	public Server getServersByName(String name) {
	    PersistenceManager pm = getPersistenceManager();
		Query query = pm.newQuery(ServerJDO.class);
		query.setFilter("name == nameParam");
		query.setOrdering("name desc");
		query.declareParameters("String nameParam");

    try {
        List<ServerJDO> results = (List<ServerJDO>) query.execute("name");
        if (results.iterator().hasNext()) {
            for (ServerJDO  e : results) {
                // ...
            }
        } else {
            // ... no results ...
        }
    } finally {
        query.closeAll();
    }
	return null;
	}
	
	public void updateServerDesc (String key, String desc) throws Exception {
	    // PersistenceManager pm = PMF.get().getPersistenceManager();
	    PersistenceManager pm = getPersistenceManager();
	    try {
	        ServerJDO e = pm.getObjectById(ServerJDO.class, key);
	        if (titleChangeIsAuthorized(e, desc)) {
	            e.desc = desc;
	        } else {
	            throw new Exception(key);
	        }
	    } finally {
//	        query.closeAll();
	        pm.close();
	    }
	}

	private boolean titleChangeIsAuthorized(ServerJDO e, String desc) {
		return true;
	}
	
	
	public int delServers(String key) throws ServerNotFoundException {
	    PersistenceManager pm = getPersistenceManager();
	    try {
	        ServerJDO e = pm.getObjectById(ServerJDO.class, key);
			pm.deletePersistent(e);
	    } catch (Exception e) {
	    	throw new ServerNotFoundException();
	    } finally {
	        pm.close();
	    }
	    return ERROR_OK;
	}

	
}
